package com.dongdongshop.shiro;

import com.dongdongshop.exception.LoginException;
import com.dongdongshop.pojo.TbAdmin;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.LoginService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class LoginRealm extends AuthorizingRealm {
    @DubboReference
    private LoginService as;

    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


    //登录(认证)方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("=====================");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        TbSeller seller = as.getSeller(username);
        if (seller == null){
            //账号不存在
            return null;
        }
        if (!seller.getStatus().equals("1")){
            throw new LoginException("账号未审核");
        }
        //1,登录成功后的用户对象,shiro会自动帮我们放到session对象中
        //2.数据库密码,shiro会自动效验密码是否正确
        //3,realName可以理解为是登陆成功后的用户名
        return new SimpleAuthenticationInfo(seller,seller.getPassword(), ByteSource.Util.bytes(seller.getSalt()),"");
    }
}
